﻿using SqlSugar;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Reflection;

namespace App.SqlSugar
{
    internal static class SqlSugarHelp
    {
        /// <summary>
        /// 表名处理
        /// </summary>
        /// <param name="type"></param>
        /// <param name="entity"></param>
        public static void table(Type type, EntityInfo entity)
        {
            var attr = type.GetCustomAttribute<TableAttribute>();
            if (attr != null)
            {
                entity.DbTableName = attr.Name;
            }
        }

        /// <summary>
        /// 表字段处理
        /// </summary>
        /// <param name="type"></param>
        /// <param name="column"></param>
        public static void column(PropertyInfo type, EntityColumnInfo column)
        {
            // 设置主键
            if (column.DbColumnName.ToLower() == "id")
            {
                column.IsPrimarykey = true;
                column.IsIdentity = true;
            }

            // 主键
            var keyAttr = type.GetCustomAttribute<KeyAttribute>();
            if (keyAttr != null)
            {
                column.IsPrimarykey = true;
                column.IsIdentity = true;
            }

            // 是否自动生成
            var attr = type.GetCustomAttribute<DatabaseGeneratedAttribute>();
            if (attr != null)
            {
                column.IsIdentity = attr.DatabaseGeneratedOption != 0;
            }

            // 设置默认值
            var defaultVal = type.GetCustomAttribute<DefaultValueAttribute>();
            if (defaultVal != null)
            {
                column.DefaultValue = defaultVal.Value?.ToString();
            }

            // 设置长度
            var stringLengthVal = type.GetCustomAttribute<StringLengthAttribute>();
            if (stringLengthVal != null)
            {
                column.Length = stringLengthVal.MaximumLength;
            }

            // 重命名字段
            var columnAttr = type.GetCustomAttribute<ColumnAttribute>();
            if (columnAttr != null && !string.IsNullOrWhiteSpace(columnAttr.Name))
            {
                column.DbColumnName = columnAttr.Name;
            }
            else
            {
                column.DbColumnName = column.DbColumnName[0].ToString().ToLower() + column.DbColumnName.Substring(1, column.DbColumnName.Count() - 1);
            }

            // 判断是否可空
            // 支持？写法
            if (column.IsPrimarykey == false && new NullabilityInfoContext().Create(type).WriteState is NullabilityState.Nullable)
            {
                column.IsNullable = true;
            }
            // 如果是string 设置为可空
            if (type.PropertyType == typeof(string) && type.GetCustomAttribute<RequiredAttribute>() == null)
            {
                column.IsNullable = true;
            }
        }
    }
}
